package com.chidopi.cdf.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ModelContextFactory {
	private static Logger logger = LoggerFactory.getLogger(ModelContextFactory.class);
	private static AnnotationConfigApplicationContext ctx = null;
	private static String[] packages = {
		"com.chidopi.market.aa.service",
		"com.chidopi.market.bookstore.service"
	};
	private ModelContextFactory() {}

	public static Object get(Class clazz)
		throws Exception
	{
		logger.debug("Into get: " + clazz.getName());
		ApplicationContext ac = getContext();
		Object obj = ac.getBean(clazz);
		if (null == obj) {
			logger.warn("ctx.getBean is null!!");
		}
		return obj;
	}

	public static Object get(String serviceName, Class clazz)
		throws Exception
	{
		logger.debug("Into get: " + serviceName + " / " + clazz.getName());
		ApplicationContext ac = getContext();
		Object obj = ac.getBean(serviceName, clazz);
		if (null == obj) {
			logger.warn("ctx.getBean is null!!");
		}
		return obj;
	}

	public static<T> T getT(Class<T> clazz)
		throws Exception
	{
		logger.debug("Into getT: " + clazz.getName());
		ApplicationContext ac = getContext();
		T obj = ac.getBean(clazz);
		if (null == obj) {
			logger.warn("ctx.getBean is null!!");
		}
		return obj;
	}

	public static<T> T getT(String serviceName, Class<T> clazz)
		throws Exception
	{
		logger.debug("Into getT: " + serviceName + " / " + clazz.getName());
		ApplicationContext ac = getContext();
		T obj = ac.getBean(serviceName, clazz);
		if (null == obj) {
			logger.warn("ctx.getBean is null!!");
		}
		return obj;
	}

	private synchronized static ApplicationContext getContext() {
		if (null == ctx) {
			logger.info("before initialize AnnotationConfigApplicationContext");
			ctx = new AnnotationConfigApplicationContext();
			//ctx.register(MgrConfig.class, AppConfig.class);
			ctx.scan(packages);
			ctx.refresh();
			logger.info("register OK!!");
		}
		return ctx;
	}
}
